<template>
    <div>
        <el-card>
            <div slot="header" class="clearfix">
                <span>{{editTitle}}</span>
                <el-button style="float: right; padding: 3px 0" type="text" @click="handleReBack(true)">
                    <i class="el-icon-back">返 回</i></el-button>
            </div>
            <el-row :gutter="10">
                <el-col :span="18">
                    <el-form :model="noticeForm" :rules="rules" ref="noticeForm" label-width="80px"
                             class="demo-noticeForm">
                        <el-form-item label="标题" prop="title">
                            <el-input v-model="noticeForm.title" :maxlength="50" show-word-limit></el-input>
                        </el-form-item>
                        <el-form-item label="类型" prop="types">
                            <el-radio-group v-model="noticeForm.types">
                                <el-radio :label="1">通知</el-radio>
                                <el-radio :label="2">公告</el-radio>
                                <el-radio :label="3">新闻</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="简要" prop="shortly">
                            <el-input type="textarea" v-model="noticeForm.shortly" :rows="4" resize="none"
                                      :maxlength="150"
                                      show-word-limit></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-upload class="upload-demo" :action="fileUploadAction" :on-remove="handleRemove"
                                       :on-success="handleUploadSuccess"
                                       multiple :limit="3" :on-exceed="handleExceed" :file-list="fileList">
                                <el-button size="small" round class="el-icon-paperclip">添加附件</el-button>
                            </el-upload>
                        </el-form-item>
                        <el-form-item label="内容" prop="content">
                            <div class="editor">
                                <div ref="toolbar" class="toolbar"></div>
                                <div ref="editor" class="text"></div>
                            </div>
                        </el-form-item>
                        <el-form-item>
                            <el-button size="small" type="primary" @click="submitForm('noticeForm','保存')"
                                       :loading="loading">保存
                            </el-button>
                            <el-button size="small" type="primary" @click="submitForm('noticeForm','保存并发布')"
                                       :loading="loading">保存并发布
                            </el-button>
                            <el-button size="medium" @click="resetForm('noticeForm')">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-col>
                <el-col :span="6">
                    <el-card shadow="never" style="height: calc(100vh - 200px)">
                        <el-input placeholder="输入关键字" v-model="filterText" prefix-icon="el-icon-search"></el-input>
                        <div class="el-tree-div">
                            <el-tree ref="tree" :data="treeData" node-key="id" class="filter-tree" empty-text="无数据"
                                     :filter-node-method="filterNode" show-checkbox
                                     :expand-on-click-node="false"
                                     :default-expand-all="expandAll"
                                     highlight-current
                                     :props="defaultProps">
                                <span class="custom-tree-node" slot-scope="{ node, data }">
                                    <span><i class="el-icon-menu"
                                             :class="node.data.icon"></i>&nbsp;{{ node.label }}</span>
                                </span>
                            </el-tree>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </el-card>
    </div>
</template>

<script>
    export default {
        name: "NoticeEdit",
        props: {
            editTitle: {
                type: String,
                required: true
            },
            rowData: {
                type: Object,
                required: false
            }
        },
        watch: {
            rowData: function (newVal, oldVal) {
                console.log(newVal, oldVal)
                if (newVal && newVal.id) {
                    this.queryDataById(newVal.id);
                } else {
                    this.noticeForm.id = null;
                }
            }
        },
        data() {
            return {
                loading: false,
                expandAll: true,
                filterText: '',
                treeData: [],
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
                noticeForm: {
                    id: null,
                    title: null,
                    addUser: null,
                    status: false,
                    shortly: null,
                    types: 1,
                    content: null,
                    attachment: [],
                    receiver: []
                },
                rules: {
                    name: [
                        {required: true, message: '请输入活动名称', trigger: 'blur'},
                        {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
                    ]
                },
                fileUploadAction: this.$commonUrlHttp + "api/rest/file/upload?path=notice_attachment",
                fileDownloadAction: this.$commonUrlHttp + "api/rest/file/download/",
                fileList: [],
                editor: null
            }
        },
        methods: {
            handleRemove(file, fileList) {
                this.fileList = fileList;
            },
            handleExceed(files, fileList) {
                this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
            },
            handleUploadSuccess(res, file) {
                if (res.code === 200) {
                    this.fileList.push({
                        name: res.data.oldName,
                        url: this.fileDownloadAction + res.data.id,
                        fileId: res.data.id
                    });
                }
            },
            handleReBack(param) {
                this.$emit("handleReBack", param);
            },
            submitForm(formName, param) {
                if ("保存并发布" === param) {
                    this.noticeForm.status = true;
                }
                this.loading = true;
                this.$refs[formName].validate((valid) => {
                        if (valid) {
                            this.noticeForm.attachment = this.fileList.map(o => {
                                return {
                                    attachmentId: o.fileId,
                                    attachmentName: o.name
                                }
                            });
                            if (this.noticeForm.id) {
                                this.$httpPut(this.$axiosBaseHttpJson, "api/rest/notice/upd", this.noticeForm).then(res => {
                                    if (res.code === 200) {
                                        this.$successMsg(param + "成功");
                                    } else {
                                        this.$errorMsg(param + "失败");
                                    }
                                    this.loading = false;
                                });
                            } else {
                                this.$httpPost(this.$axiosBaseHttpJson, "api/rest/notice/save", this.noticeForm).then(res => {
                                    if (res.code === 200) {
                                        this.$successMsg(param + "成功");
                                    } else {
                                        this.$errorMsg(param + "失败");
                                    }
                                    this.loading = false;
                                });
                            }
                            this.$nextTick(()=>{
                                this.$sendWSPush("", {});
                            });
                        } else {
                            console.log('error submit!!');
                            return false;
                        }
                    }
                );
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
                this.editor.txt.clear();
            }
            ,
            //静态过滤方法
            filterNode(value, data) {
                if (!value) return true;
                return data.label.indexOf(value) !== -1;
            }
            ,
            // 创建编辑器
            createEditor() {
                const E = require('wangeditor');
                // 引用
                this.editor = new E(this.$refs.toolbar, this.$refs.editor);
                this.editor.customConfig.uploadImgShowBase64 = false // base 64 存储图片
                this.editor.customConfig.uploadImgServer = 'http://otp.cdinfotech.top/file/upload_images'// 配置服务器端地址
                this.editor.customConfig.uploadImgHeaders = {}// 自定义 header
                this.editor.customConfig.uploadFileName = 'file' // 后端接受上传文件的参数名
                this.editor.customConfig.uploadImgMaxSize = 2 * 1024 * 1024 // 将图片大小限制为 2M
                this.editor.customConfig.uploadImgMaxLength = 6 // 限制一次最多上传 3 张图片
                this.editor.customConfig.uploadImgTimeout = 3 * 60 * 1000 // 设置超时时间

                // 配置菜单
                this.editor.customConfig.menus = [
                    'head', // 标题
                    'bold', // 粗体
                    'fontSize', // 字号
                    'fontName', // 字体
                    'italic', // 斜体
                    'underline', // 下划线
                    'strikeThrough', // 删除线
                    'foreColor', // 文字颜色
                    'backColor', // 背景颜色
                    'link', // 插入链接
                    'list', // 列表
                    'justify', // 对齐方式
                    'quote', // 引用
                    'emoticon', // 表情
                    'image', // 插入图片
                    'table', // 表格
                    'video', // 插入视频
                    'code', // 插入代码
                    'undo', // 撤销
                    'redo', // 重复
                    'fullscreen' // 全屏
                ];

                this.editor.customConfig.uploadImgHooks = {
                    fail: (xhr, editor, result) => {
                        // 插入图片失败回调
                    },
                    success: (xhr, editor, result) => {
                        // 图片上传成功回调
                    },
                    timeout: (xhr, editor) => {
                        // 网络超时的回调
                    },
                    error: (xhr, editor) => {
                        // 图片上传错误的回调
                    },
                    customInsert: (insertImg, result, editor) => {
                        // 图片上传成功，插入图片的回调
                        //result为上传图片成功的时候返回的数据，这里我打印了一下发现后台返回的是data：[{url:"路径的形式"},...]
                        // console.log(result.data[0].url)
                        //insertImg()为插入图片的函数
                        //循环插入图片
                        // for (let i = 0; i < 1; i++) {
                        // console.log(result)
                        let url = "http://otp.cdinfotech.top" + result.url
                        insertImg(url)
                        // }
                    }
                };
                this.editor.customConfig.onchange = (html) => {
                    this.noticeForm.content = html;
                };
                this.editor.create();
            }
            ,
            queryDataById(id) {
                if (id)
                    this.$httpGet(this.$axiosBaseHttp, "api/rest/notice/one", {id: id}).then(res => {
                        if (res.code === 200) {
                            this.noticeForm = res.data;
                            this.fileList = this.noticeForm.attachment.map(o => {
                                return {
                                    name: o.attachmentName,
                                    url: this.fileDownloadAction + o.attachmentId,
                                    fileId: o.attachmentId
                                }
                            });
                            this.editor.txt.html(this.noticeForm.content);
                        }
                    });
            }
            ,
        },
        mounted() {
            this.createEditor();
            this.resetForm("noticeForm");
            this.queryDataById(this.rowData.id);
            this.$httpGet(this.$axiosBaseHttp, "api/rest/menuInfo/tree", {}).then(res => {
                if (res.code === 200) {
                    this.treeData = res.data;
                    this.loading = false;
                }
            })
        }
        ,
        destroyed() {

        }
    }
</script>

<style scoped lang="scss">
    .editor {
        width: 100%;
        margin: 0 auto;
        position: relative;
        z-index: 0;
    }

    .toolbar {
        border: 1px solid #ccc;
        border-bottom: transparent;
    }

    .text {
        border: 1px solid #ccc;
        min-height: 250px;
    }

    /deep/ .w-e-text {
        overflow-y: unset;

        p {
            min-height: 250px;
        }
    }
</style>
